package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.Collection;
import com.repository.CollectionRepository;
import com.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 11:06 2019/1/9
 */
@Service
public class CollectionServiceImp implements CollectionService {

    @Autowired
    private CollectionRepository collectionRepository;

    @Override
    public Collection findOne(int id){
        Optional<Collection> optionalUser = collectionRepository.findById(id);
        return optionalUser.get();
    }

    /**
     * 添加收藏
     * @param bean
     * @return
     */
    @Transactional
    @Override
    public Result create(Collection bean){
        List<Collection> resList = collectionRepository.findAllByUserId(bean.getUserId());
        for (int i = 0; i < resList.size(); i++){
            if(resList.get(i).getArticleId() == bean.getArticleId()){
                return Base.error("你已收藏过该文章");
            }
        }

        bean.setCreatedAt(new Date());
        collectionRepository.save(bean);

        return Base.success();
    }

    /**
     * 根据用户id分页查询收藏的文章
     * @param bean
     * @return
     */
    @Override
    public Result indexByUserId(Collection bean){
        Pageable pageable = new PageRequest(bean.getPage(),bean.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Collection> page = collectionRepository.findAllByUserId(bean.getUserId(),pageable);
        int total = collectionRepository.countByUserId(bean.getUserId());
        int maxPage = total/bean.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }


}
